<template>
    <div style="height: 100%;">
        <navbar :title="title" :backCallback="back">
            <template #right>
                <span class="write-btn-right font-size15 head-right cur" @click="submit(false)">{{ $t("mod_submit") }}</span><!--交卷-->
            </template>
        </navbar>
        <div class="exam-nav bottom-shadow-02" style="position: absolute;top: 56px;left: 0;width: calc(100% - 30px);">
            <div><!--已答/未答-->
                <p class="margin-right20">{{ $t("mod_anwser") }} <span style="color:#1a1a1a;">({{answered.length}}/{{topicList.length}})</span></p>
                <!--<p>{{ $t("mod_no_anwser") }} <span style="color:#1a1a1a;">({{topicList.length - answered.length}})</span></p>-->
            </div>
            <div><!--剩余时间-->
                <span class="color999">{{ $t("mod_timeLeft") }} </span><span class="color518">({{timing}})</span>
            </div>
        </div>
        <div class="content" id="content-box" style="overflow: auto;background: #ffffff;">
            <!--body-->
            <div class="exam-body">
                <div v-for="(item, index) in topicList" :key="index" :ref="index">
                    <!--MC 单选-->
                    <div v-show="(questionType === 'only' && topicIndex === index) || questionType ==='many'" v-if="item.type == 'MC' && item.logicType == 'CHOICE_SINGLE'" class="topic-mc white-bg" style="padding: 60px 15px 30px;">
                        <div>
                            <p class="font-size16 margin-bottom10">[{{ $t("Mc_sin") }}]</p><!--单选题-->
                            <p class="font-size16" style="margin-bottom: 40px;">{{index + 1}}.
                                <span v-html="$xss(imgHandle(item.subject))"></span>
                            </p>
                            <ul class="module-list-06 selection-01">
                                <li  :class="{'cur': item.answerOptions && item.answerOptions[0] == option.id}" @click="selectAnswer('MC', $index + 1, item.id, index)" v-for="(option, $index) in item.options" :key="$index">
                                    <i></i><span v-html="$xss(imgHandle(option.subject))"></span>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <!--多选-->
                    <div v-show="(questionType === 'only' && topicIndex === index) || questionType ==='many'" v-if="item.type == 'MC' && (item.logicType == 'CHOICE_AND' || item.logicType== 'CHOICE_OR')" class="topic-mc white-bg" style="padding: 60px 15px 30px;">
                        <div>
                            <p class="font-size16 margin-bottom10">[{{ $t("Mc") }}]</p><!--多选题-->
                            <p class="font-size16" style="margin-bottom: 40px;">{{index + 1}}.
                                <span v-html="$xss(imgHandle(item.subject))"></span>
                            </p>
                            <ul class="module-list-06 selection-02">
                                <li :class="{'cur': item.answerOptions && item.answerOptions.includes(option.id )}" @click="selectAnswer('MC_AND', $index + 1, item.id, index)" v-for="(option, $index) in item.options" :key="$index">
                                    <i></i><span v-html="$xss(imgHandle(option.subject))"></span>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <!--FB 填空题-->
                    <div v-show="(questionType === 'only' && topicIndex === index) || questionType ==='many'" v-if="item.type == 'FB'" class="topic-fb" style="padding: 60px 15px 30px;">
                        <div class="font-size16">
                            <p class="font-size16 margin-bottom10">[{{ $t("FB") }}]</p><!--填空题-->
                            <p>{{index + 1}}.<span v-html="$xss($options.filters.filterSpace(item.subject, item.id))"></span></p>
                        </div>
                        <div v-for="(childId, topic) in statisticsSpace(item.subject)" :key="topic">
                            <div>{{ $t("FB_label") }} {{topic + 1}}</div>
                            <div class="fb-space"  v-showText="item.answerFillBlank ? item.answerFillBlank[topic] : ''" :name="`${item.id}${topic}`" :ref="`fb${item.id}`" contenteditable="true" :placeholder="$t('answer_prompt_1')" @input="selectAnswer('FB',`fb${item.id}`,item.id, index)"></div>
                            <p style="margin: 0;display: none" :ref="`fbError${item.id}${topic}`" class="font-size11 colorfd3 warning-red-tan warning">{{ $t('exceeded_word_range_tips', {'value': '200'}) }}</p>
                        </div>
                    </div>
                    <!--TF 判断题-->
                    <div v-show="(questionType === 'only' && topicIndex === index) || questionType ==='many'" v-if="item.type == 'TF'" class="topic-mc white-bg" style="padding: 60px 15px 30px;">
                        <div>
                            <p class="font-size16 margin-bottom10">[{{ $t("TF") }}]</p><!--判断题-->
                            <p class="font-size16" style="margin-bottom: 40px;">{{index + 1}}.
                                <span v-html="$xss(item.subject)"></span>
                            </p>
                            <ul class="module-list-06 selection-01">
                                <li :class="{'cur': item.answerJudgment && item.answerJudgment  == true}" @click="selectAnswer('TF', true, item.id, index)">
                                    <i></i>{{ $t("lab_true") }}
                                </li>
                                <li :class="{'cur':  item.answerJudgment == false}" @click="selectAnswer('TF', false, item.id, index)">
                                    <i></i>{{ $t("lab_false") }}
                                </li>
                            </ul>
                        </div>
                    </div>
                    <!--ES 问答题-->
                    <div v-show="(questionType === 'only' && topicIndex === index) || questionType ==='many'" v-if="item.type == 'ES'" >
                        <div class="topic-es" style="padding: 60px 15px 30px;">
                            <p class="font-size16 margin-bottom10">[{{ $t("ES") }}]</p><!--问答题-->
                            <div class="font-size16">
                                {{index + 1}}. <span v-html="$xss(item.subject)"></span>
                            </div>
                            <div class="topic-es-box" contenteditable="true" :placeholder="$t('answer_prompt_2')" v-showText="item.answerShort" :ref="`es${item.id}`" @input="selectAnswer('ES',`es${item.id}`,item.id, index)"></div>
                            <p style="margin: 0;display: none" :ref="`esError${item.id}`" class="font-size11 colorfd3 warning-red-tan warning">{{ $t('exceeded_word_range_tips', {'value': '1000'}) }}</p>
                        </div>
                    </div>
                    <!--MT 配对题-->
                    <div v-if="(questionType === 'only' && topicIndex === index) || questionType ==='many'">
                        <div v-if="item.type == 'MT'" class="topic-mt" style="background: #f5f5f5;">
                            <div style="padding: 60px 15px 0;">
                                <p class="font-size16 margin-bottom10">[{{ $t("MT") }}]</p><!--配对题-->
                                <div class="font-size16">
                                    {{index + 1}}. <span v-html="$xss(item.subject)"></span>
                                </div>
                                <scroll-tab :no-scroll="true" class="tab-box tab-box-2">
                                    <tab-item @on-item-click="(event) => onItemClick(item, index,event)">
                                        <div style="background: #f5f5f5"><!--来源-->
                                            {{ $t("selected_from") }}
                                        </div>
                                    </tab-item>
                                    <tab-item @on-item-click="(event) => onItemClick(item, index,event)">
                                        <div style="background: #f5f5f5"><!--目标-->
                                            {{ $t("cos_target") }}
                                        </div>
                                    </tab-item>
                                </scroll-tab>
                            </div>
                            <!--options-->
                            <div style="background: #ffffff;padding: 30px 15px 0;" v-show="item.switchTabIndex == 0" >
                                <div v-for="(topic, index) in item.options" :key="index" style="margin-bottom: 50px;">
                                    <div>
                                        {{letterList[index]}}. <span v-html="$xss(topic.subject)"></span>
                                    </div>
                                    <div style="margin-top: 20px;">
                                        <img v-if="topic.image" :src="matchingImg(topic.image)" alt="" width="150" height="150">
                                    </div>
                                </div>
                            </div>
                            <!--matchingOptions-->
                            <div style="padding: 30px 15px 0;background: #ffffff;" class="topic-mt-matching" v-show="item.switchTabIndex == 1">
                                <div v-for="(topic, index) in item.matchingOptions" :key="index" style="margin-bottom: 50px;">
                                    <div class="clearfix" style="width: 100%;">
                                        ({{index + 1}})
                                        <div class="topic-mt-matching-btn" style="float: right;" @click="mtTipsCLick(item, item.id, index+1)">
                                            {{item.answerMatching && item.answerMatching[index+1] ? $t("selected_from") + ' ' + letterList[item.answerMatching[index+1] - 1] : $t("selecting_source")}}
                                        </div><!--选择来源-->
                                    </div>
                                    <div style="margin-top: 20px;">
                                        <div v-html="$xss(topic.subject)"></div>
                                        <img style="margin-top: 20px;" v-if="topic.image" :src="matchingImg(topic.image)" alt="" width="150" height="150">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!--SR 录音题-->
                    <div>
                        <div v-show="(questionType === 'only' && topicIndex === index) || questionType ==='many'" v-if="item.type == 'SR'" class="topic-es" style="padding: 60px 15px 30px;">
                            <sr-ques :info="item" :currentIndex="index" :examId="examId" :thkId="appId" @on-select="selectAnswer" :saveUrl="item.answerShort"></sr-ques>
                        </div>
                    </div>
                    <!-- SI 情景题 -->
                    <div v-show="(questionType === 'only' && topicIndex === index) || questionType ==='many'" v-if="item.type == 'SI'" class="topic-mc white-bg type-si"  style="padding: 60px 15px 30px;">
                        <div>
                            <p class="font-size16 margin-bottom10">[{{ $t("SI") }}]</p>
                            <p class="font-size16" style="margin-bottom: 40px;">{{index + 1}}.<span v-html="$xss(item.subject)"></span></p>
                        </div>
                        <div v-for="(items,index1) in item.questionInfoList" :key="index1">
                            <!-- SR 录音题 -->
                            <div v-if="items.type == 'SR'" class="topic-es" style="padding-bottom: 30px;">
                                <sr-ques :info="items" :currentIndex="index" :currentSubIndex="index1" :examId="examId" :thkId="appId" @on-select="siSelectAnswer" :saveUrl="items.answerShort"></sr-ques>
                            </div>
                            <!--MC 单选-->
                            <div v-if="items.type == 'MC' && items.logicType == 'CHOICE_SINGLE'" class="topic-mc white-bg" style="padding: 0px 15px 30px;">
                                <div>
                                    <p class="font-size16 margin-bottom10">[{{ $t("Mc_sin") }}]</p><!--单选题-->
                                    <p class="font-size16" style="margin-bottom: 40px;">({{index1 + 1}}).
                                        <span v-html="$xss(items.subject)"></span>
                                    </p>
                                    <ul class="module-list-06 selection-01">
                                        <li  :class="{'cur': items.answerOptions && items.answerOptions[0] == option.id}"
                                         @click="siSelectAnswer('MC', $index + 1, items.id, index,index1)" v-for="(option, $index) in items.options" :key="$index">
                                            <i></i><span v-html="$xss(option.subject)"></span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <!--多选-->
                            <div v-if="items.type == 'MC' && (items.logicType == 'CHOICE_AND' || items.logicType== 'CHOICE_OR')" class="topic-mc white-bg" style="padding: 0px 15px 30px;">
                                <div>
                                    <p class="font-size16 margin-bottom10">[{{ $t("Mc") }}]</p><!--多选题-->
                                    <p class="font-size16" style="margin-bottom: 40px;">({{index1 + 1}}).
                                        <span v-html="$xss(items.subject)"></span>
                                    </p>
                                    <ul class="module-list-06 selection-02">
                                        <li :class="{'cur': items.answerOptions && items.answerOptions.includes(option.id )}"
                                        @click="siSelectAnswer('MC_AND', $index + 1, items.id, index,index1)" v-for="(option, $index) in items.options" :key="$index">
                                            <i></i><span v-html="$xss(option.subject)"></span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <!--FB 填空题-->
                            <div v-if="items.type == 'FB'" class="topic-fb" style="padding: 0px 15px 30px;">
                                <div class="font-size16">
                                    <p class="font-size16 margin-bottom10">[{{ $t("FB") }}]</p><!--填空题-->
                                    <p>({{index1 + 1}}).<span v-html="$xss($options.filters.filterSpace(items.subject, items.id))"></span></p>
                                </div>
                                <div v-for="(childId, topic) in statisticsSpace(items.subject)" :key="topic">
                                    <div>{{ $t("FB_label") }} {{topic + 1}}</div>
                                    <div class="fb-space"  v-showText="items.answerFillBlank ? items.answerFillBlank[topic] : ''" :name="`${items.id}${topic}`" :ref="`fb${items.id}`" contenteditable="true" :placeholder="$t('answer_prompt_1')"
                                     @input="siSelectAnswer('FB',`fb${items.id}`,items.id, index,index1)"></div>
                                    <p style="margin: 0;display: none" :ref="`fbError${items.id}${topic}`" class="font-size11 colorfd3 warning-red-tan warning">{{ $t('exceeded_word_range_tips', {'value': '200'}) }}</p>
                                </div>
                            </div>
                            <!--TF 判断题-->
                            <div v-if="items.type == 'TF'" class="topic-mc white-bg" style="padding: 0px 15px 30px;">
                                <div>
                                    <p class="font-size16 margin-bottom10">[{{ $t("TF") }}]</p><!--判断题-->
                                    <p class="font-size16" style="margin-bottom: 40px;">({{index1 + 1}}).
                                        <span v-html="$xss(items.subject)"></span>
                                    </p>
                                    <ul class="module-list-06 selection-01">
                                        <li :class="{'cur': items.answerJudgment && items.answerJudgment  == true}"
                                         @click="siSelectAnswer('TF', true, items.id, index,index1)">
                                            <i></i>{{ $t("lab_true") }}
                                        </li>
                                        <li :class="{'cur':  items.answerJudgment == false}"
                                         @click="siSelectAnswer('TF', false, items.id, index,index1)">
                                            <i></i>{{ $t("lab_false") }}
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <!--ES 问答题-->
                            <div v-if="items.type == 'ES'" >
                                <div class="topic-es" style="padding: 0px 15px 30px;">
                                    <p class="font-size16 margin-bottom10">[{{ $t("ES") }}]</p><!--问答题-->
                                    <div class="font-size16">
                                        ({{index1 + 1}}). <span v-html="$xss(items.subject)"></span>
                                    </div>
                                    <div class="topic-es-box" contenteditable="true" :placeholder="$t('answer_prompt_2')" v-showText="items.answerShort" :ref="`es${items.id}`"
                                     @input="siSelectAnswer('ES',`es${items.id}`,items.id, index,index1)"></div>
                                    <p style="margin: 0;display: none" :ref="`esError${items.id}`" class="font-size11 colorfd3 warning-red-tan warning">{{ $t('exceeded_word_range_tips', {'value': '1000'}) }}</p>
                                </div>
                            </div>
                            <!--MT 配对题-->
                            <div v-if="items.type == 'MT'" >
                                <div class="topic-mt" style="background: #f5f5f5;">
                                    <div style="padding: 0px 15px 0;">
                                        <p class="font-size16 margin-bottom10">[{{ $t("MT") }}]</p><!--配对题-->
                                        <div class="font-size16">
                                            ({{index1 + 1}}). <span v-html="$xss(items.subject)"></span>
                                        </div>
                                        <scroll-tab :no-scroll="true" class="tab-box tab-box-2">
                                            <tab-item @on-item-click="(event) => onItemClick(item, index,event,index1)">
                                                <div style="background: #f5f5f5"><!--来源-->
                                                    {{ $t("selected_from") }}
                                                </div>
                                            </tab-item>
                                            <tab-item @on-item-click="(event) => onItemClick(item, index,event,index1)">
                                                <div style="background: #f5f5f5"><!--目标-->
                                                    {{ $t("cos_target") }}
                                                </div>
                                            </tab-item>
                                        </scroll-tab>
                                    </div>
                                    <!--options-->
                                    <div style="background: #ffffff;padding: 30px 15px 0;" v-show="items.switchTabIndex == 0" >
                                        <div v-for="(topic, index) in items.options" :key="index" style="margin-bottom: 50px;">
                                            <div>
                                                {{letterList[index]}}. <span v-html="$xss(topic.subject)"></span>
                                            </div>
                                            <div style="margin-top: 20px;">
                                                <img v-if="topic.image" :src="matchingImg(topic.image)" alt="" width="150" height="150">
                                            </div>
                                        </div>
                                    </div>
                                    <!--matchingOptions-->
                                    <div style="padding: 30px 15px 0;background: #ffffff;" class="topic-mt-matching" v-show="items.switchTabIndex == 1">
                                        <div v-for="(topic, indexs) in items.matchingOptions" :key="indexs" style="margin-bottom: 50px;">
                                            <div class="clearfix" style="width: 100%;">
                                                ({{indexs + 1}})
                                                <div class="topic-mt-matching-btn" style="float: right;" @click="mtTipsCLick(items, items.id, indexs+1,index)">
                                                    {{items.answerMatching && items.answerMatching[indexs+1] ? $t("selected_from") + ' ' + letterList[items.answerMatching[indexs+1] - 1] : $t("selecting_source")}}
                                                </div><!--选择来源-->
                                            </div>
                                            <div style="margin-top: 20px;">
                                                <div v-html="$xss(topic.subject)"></div>
                                                <img style="margin-top: 20px;" v-if="topic.image" :src="matchingImg(topic.image)" alt="" width="150" height="150">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="exam-foot">
            <div @click="answerLetter = true"><!--答题卡-->
                {{ $t("mod_ans_card") }}
            </div>
            <div v-if=" questionType !=='many'">
                <div @click="prev" :class="{'cur': topicIndex == 0}"><!--上一题-->
                    {{ $t("mod_prev") }}
                </div>
                <div @click="next" :class="{'cur': questionType === 'many'|| topicList.length - 1 == topicIndex}"><!--下一题-->
                    {{ $t("mod_next") }}
                </div>
            </div>
        </div>
        <!--tip-->
        <van-dialog
            v-model="mtTips"
            :show-confirm-button="false"
            >
            <div style="text-align: center;">
                <div style="padding: 20px 0;font-size: 18px;">{{ $t("selecting_target", {'value': '(' + mtOption.index + ')'}) }}</div><!--选择目标/来源-->
                <div style="color: #999999;font-size: 14px;margin-bottom: 15px;">{{ $t("selecting_source_tips") }}</div><!--重复选择「来源」会将前一个选择项清空-->
                <ul class="module-list-06 selection-01 mt-selection">
                    <li v-for="(item, index) in mtOption.options " @click="mtConfirm(index+1, mtOption.index)" :key="index" :class="{'cur': mtOption.answerMatching && mtOption.answerMatching[mtOption.index] == index+1}">
                        <i></i>{{item.subject}}
                        <span v-show="mtOption.answerMatching && Object.values(mtOption.answerMatching).includes(index+1) && mtOption.answerMatching[mtOption.index] != index+1" style="float: right;">{{ $t("selecting_already") }}</span><!--已选-->
                    </li>
                </ul>
            </div>
        </van-dialog>
        <van-dialog
            v-model="subTips"
            show-cancel-button
            :title="subType"
            :cancelButtonText="$t('cancel')"
            :confirm-button-text="$t('sure')"
            @confirm="submit(true)"
            >
        </van-dialog>
        <!--答题卡-->
        <div class="answer-letter" v-show="answerLetter">
            <div class="answer-letter-content">
                <div>
                    <div class="answer-letter-close">
                        <i class="close-icon-02" @click="answerLetter = false"></i>
                    </div>
                    <div class="answer-letter-title">{{ $t("mod_ans_card") }}</div><!--答题卡-->
                    <div class="answer-letter-tip">
                        <div><!--已回答-->
                            {{ $t("mod_anwsered") }}
                        </div>
                        <div><!--未回答-->
                            {{ $t("mod_wait_anwser") }}
                        </div>
                    </div>
                </div>
                <div class="answer-letter-list">
                    <ul class="clearfix">
                        <li @click="jumpTopic(index, item)" v-for="(item, index) in topicList" :key="index" :class="{'cur': answered.includes(item.id)}">
                            {{index+1}}
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <!--loading-->
        <div class="loading" v-if="subLoading">
            <div >
                <div style="width: 33px;height: 33px;">
                    <img src="../../../static/images/loading.gif" alt="" style="width: 100%"/>
                </div>
                <div>{{ $t("lab_loading") }}</div><!--加载中...-->
            </div>
        </div>
        <!--测验已结束，请立即交卷。-->
        <van-dialog
            v-model="controlTips"
            :confirm-button-text="$t('sure')"
            :title="$t('exam_tips_1')"
            @confirm="submit(true)"
            >
        </van-dialog>
        <!--确定退出测验？系统会保存您的答题记录和答题时间。-->
        <van-dialog
            v-model="leave"
            show-cancel-button
            :cancelButtonText="$t('cancel')"
            :confirm-button-text="$t('sure')"
            :title="canSave?$t('exam_tips_2'):$t('exam_tips_2_nosave')"
            @confirm="confirmBack()"
            >
        </van-dialog>
        <!--errorTip-->
        <van-dialog
            v-model="error"
            :show-confirm-button="false"
            >
            <div style="text-align: center;">
                <div style="font-size: 18px;padding: 20px 0;">{{ $t("exam_tips_3") }}</div><!--题目答案超出规定字数，请修改-->
                <div style="color: #999999;font-size: 14px;">{{ $t("exam_tips_4") }}</div><!--点击下列题目序号直接修改-->
                <div style="overflow:hidden;">
                    <ul>
                        <li class="errorList" @click="jumpTopic(item)" v-for="item in errorList" :key="item">{{item + 1}}</li>
                    </ul>
                </div>
            </div>
        </van-dialog>
        <van-dialog
            v-model="noTopicListTips"
            :confirm-button-text="$t('sure')"
            :title="$t('exam_tips_5')"
            @confirm="confirmBack()"
            >
        </van-dialog>
        <!--submit error tips-->
        <van-dialog
            v-model="sumitErrorTips"
            :confirm-button-text="$t('sure')"
            :title="tipsType"
            @confirm="confirmBack()"
            >
        </van-dialog>
        <!--tips-->
        <div class="toast-box-03" v-if="assTip">
            <p class="toast-box-03-title">{{ tipsType }}</p>
        </div>
        <face-modal ref="faceExam" :visibleModal="visibleModal" @takePictures='takePictures' @takingError='takingError' :busId='examId'
            :distinguishType="ufrBusType" :ufrId="ufrId" @closeFace="closeFace">
            <div slot="down" style="text-align:center;padding:10px 0 0;color:#F56C6C;font-size:16px">{{$t('after_quite', {'value': second})}}</div>
        </face-modal>
    </div>
</template>

<script>
import {tabItem, scrollTab} from '@/repeatComponents/scrollTab/index';
import faceModal from '@/components/faceModal/faceModal';
import srQues from '@/components/course/components/sr-ques';
let that;
export default {
    name: 'Exam',
    components: {tabItem, scrollTab, faceModal, srQues},
    data() {
        return {
            examId: this.$route.params.modId,
            appId: this.$route.params.tkhId,
            itmId: this.$route.params.itmId,
            siIndex: 0,
            topicList: [], //题目列表
            title: '', //测验题目
            topicIndex: 0, //显示当前题目
            letterList: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
            switchTabIndex: 0,
            userAnswer: {},
            mtTips: false,
            mtOption: {
                id: '',
                list: []
            },
            selectMt: {},
            subId: 0,
            allInfo: {},
            examIntervalTime: null, //考试时间定时器
            saveTime: null, //保存时间
            timing: '', //时间显示
            answered: [], //已回答
            answerLetter: false,
            subTips: false, //
            subType: '',
            subLoading: false,
            controlTips: false,
            leave: false,
            error: false,
            errorList: [], //校验错误题目
            noTopicListTips: false, //动态测验没有题目弹出层
            assTip: false,
            tipsType: '',
            confirmBackFlag: false, //是否确认推出测验，用于游览器和app端按键返回的二次校验
            autoSaveLock: false,
            sumitErrorTips: false, //提交失败提示
            timeOut: false, //强制交卷
            second: 30, //人脸倒计时
            intervalNull: null,
            visibleModal: false,
            faceTime: 0,
            faceIndex: 0,
            faceList: [],
            ufrId: 0,
            ufrBusType: this.$route.query.itmExamInd === '1' || this.$route.query.itmExamInd === 1 ? 'ONLINE_EXAM_TEST' : 'ONLINE_COURSE_TEST',
            manyFaceList: [], // 用来存放一屏多题时，可视区域内需要人脸识别的题目节点
            questionType: 'only', // 题目展示方式
            canSave: true
        };
    },
    methods: {
        getFaceTime() { // 培训项目-线上课程（视频）- 获取人脸识别随机节点
            this.$axios({
                method: 'POST',
                url: `/app/api/trainee/user-face-gather/getCourseModNode`,
                data: {
                    itmId: this.$route.params.itmId, // 课程ID或考试ID
                    ufrBusId: this.$route.params.modId,
                    // ONLINE_COURSE_VOD:在线课程-视频;ONLINE_COURSE_TEST:在线课程-测验;ONLINE_EXAM_TEST:在线考试-测验;TRAIN_COURSE_VOD:培训项目-线上课程视频;TRAIN_COURSE_TEST:培训项目-线上考试测验
                    ufrBusType: this.ufrBusType
                }
            }).then(res => {
                this.faceList = res.data;
                this.entrance();
            });
        },
        closeFace() {
            clearInterval(this.intervalNull);
            this.visibleModal = false;
            this.$refs.faceExam && this.$refs.faceExam.closeCamera();
            this.timeOut = true; //标志强制交卷退出状态
            this.confirmBackFlag = true;
            this.autoSave();
            this.$router.go(-1);
        },
        // 考试中人脸倒计时
        countDown() {
            clearInterval(this.intervalNull);
            this.intervalNull = setInterval(() => {
                this.second--;
                if (this.second <= 0) { //时间到了自动提交
                    clearInterval(this.intervalNull);
                    this.visibleModal = false;
                    this.$refs.faceExam && this.$refs.faceExam.closeCamera();
                    this.timeOut = true; //标志强制交卷退出状态
                    this.confirmBackFlag = true;
                    this.autoSave();
                    this.$router.go(-1);
                    // this.submit(true);
                }
            }, 1000);
        },
        // 人脸识别弹出
        isFacePhoto(node = 0) {
            const curNode = node || this.topicIndex;
            const faceNode = this.faceList ? this.faceList.find(node => Number(node.ufrNode) === (curNode + 1)) : '';
            if (faceNode) {
                if (faceNode.ufrStatus === 'ON') {
                    this.faceIndex++;
                } else if (faceNode.ufrStatus === 'OFF') {
                    this.$nextTick(() => {
                        this.visibleModal = true;
                    });
                    this.ufrId = faceNode.ufrId;
                    this.faceIndex++;
                    this.countDown();
                }
            }
        },
        takePictures() {
            this.second = 30;
            clearInterval(this.intervalNull);
            this.visibleModal = false;
            this.getTime(this.saveTime);
            // 人脸识别成功后，改变列表的OFF为ON
            const indexNode = this.faceList.findIndex(node => node.ufrId === this.ufrId);
            this.$set(this.faceList[indexNode], 'ufrStatus', 'ON');
            if (this.questionType === 'many') {
                if (this.manyFaceList[0] === (this.faceList[indexNode].ufrNode - 1)) {
                    this.manyFaceList.shift();
                }
                if (this.manyFaceList.length > 0) {
                    // 人脸识别
                    this.isFacePhoto(this.manyFaceList[0]);
                }
                // console.log('可视区域内需要人脸识别后===的节点的下标', this.manyFaceList);
            }
        },
        // 人脸错误信息
        takingError() {
            this.visibleModal = false;
        },
        onlineCalculation(type) {
            this.$axios({
                method: 'GET',
                url: `/app/api/data/kanban/online/${type}/calculate`
            }).then(res => {

            });
        },
        /**
         * 用户第一次进入考试获取最新的试题
         */
        firstEntry() {
            this.$axios({
                method: 'GET',
                url: `/app/exam/cache/info`,
                params: {
                    examId: this.examId,
                    subId: 0
                }
            }).then(res => {
                this.canSave = res.data.canSave;
                this.topicList = res.data.questions;
                this.isFacePhoto();
                if (this.topicList.length === 0) {
                    this.noTopicListTips = true;
                } else {
                    this.switchTabMT(this.topicList);
                }
                this.getTime(res.data.timeLimit);
                this.subId = res.data.subId;
                this.allInfo = res.data; // 改参数待定
                this.title = res.data.title;
            });
        },
        switchTabMT(topicList) {
            console.log(topicList, 'topicList111');
            topicList.forEach(item => {
                if (item.type === 'MT') {
                    item.switchTabIndex = 0;
                } else if (item.type === 'SI') {
                    item.questionInfoList.forEach(items => {
                        if (items.type === 'MT') {
                            items.switchTabIndex = 0;
                        }
                    });
                }
            });
        },
        /**
         * 判断用户是否由之前的考试试题
         * @constructor
         */
        entrance() {
            this.$axios({
                method: 'GET',
                url: `/app/exam/cache/provisional/save`,
                params: {
                    examId: this.examId,
                    appId: this.appId
                }
            }).then(res => {
                this.questionType = this.$route.query.questionType;
                if (!res.data && (res.data.examInfo == null)) {
                    this.firstEntry();
                } else {
                    this.topicList = res.data.examInfo.questions;
                    this.switchTabMT(this.topicList);
                    this.questionType = this.$route.query.questionType;
                    if (this.topicList.length === 0) {
                        this.noTopicListTips = true;
                    }
                    this.title = res.data.examInfo.title;
                    this.subId = res.data.subId;

                    this.allInfo = res.data.examInfo;
                    this.getTime(res.data.remainingTime || res.data.examInfo.timeLimit);
                    let userAnswer = res.data.userAnswer;
                    for (let index = 0; index < this.topicList.length; index++) {
                        switch (this.topicList[index].type) {
                        case 'MC':
                            this.$set(this.topicList[index], 'answerOptions', userAnswer[this.topicList[index].id].answerOptions);
                            break;
                        case 'TF':
                            this.$set(this.topicList[index], 'answerJudgment', userAnswer[this.topicList[index].id].answerJudgment);
                            break;
                        case 'FB':
                            this.$set(this.topicList[index], 'answerFillBlank', userAnswer[this.topicList[index].id].answerFillBlank);
                            break;
                        case 'ES':
                            this.$set(this.topicList[index], 'answerShort', userAnswer[this.topicList[index].id].answerShort);
                            break;
                        case 'MT':
                            this.$set(this.topicList[index], 'answerMatching', userAnswer[this.topicList[index].id].answerMatching);
                            break;
                        case 'SR':
                            this.$set(this.topicList[index], 'answerShort', userAnswer[this.topicList[index].id].answerShort);
                            break;
                        }
                    }
                    this.getAnswered();
                    // console.log('题目展示方式-------this.questionType--------', this.questionType);
                    if (this.questionType === 'only') {
                        // 人脸识别
                        this.isFacePhoto();
                    } else {
                        setTimeout(() => {
                            this.handleScroll();
                        }, 100);
                    }
                }
            });
        },
        /**
         * 填空题数量
         * @param value
         * @returns {*}
         */
        statisticsSpace(value) {
            return value.match(/\[_]/g).length;
        },
        onItemClick(item, index, event, index1 = 0) {
            if (item.type === 'SI') {
                this.$set(this.topicList[index].questionInfoList[index1], 'switchTabIndex', event);
                this.$forceUpdate();
            } else {
                this.$set(this.topicList[index], 'switchTabIndex', event);
                this.$forceUpdate();
            }
        },
        /**
         * 下一题
         */
        next() {
            if (this.questionType === 'many' || this.topicIndex === this.topicList.length - 1) {
                return;
            }
            this.topicIndex += 1;
            this.isFacePhoto();
        },
        prev() {
            if (this.topicIndex === 0) {
                return;
            }
            this.topicIndex -= 1;
            this.isFacePhoto();
        },
        /**
         * 选择答案
         * @param type
         * @param answer
         * @param id
         * @param index
         */
        selectAnswer(type, answer, id, index) {
            console.log(type, answer, id, index);
            //选择题乱序
            let _answer;
            switch (type) {
            case 'MC':
                _answer = this.topicList[index].options[answer - 1].id;
                if (this.topicList[index].shuffle && this.topicList[index].shuffle === 'Y') {
                    this.$set(this.topicList[index], 'answerOptions', [_answer]);
                    break;
                } else {
                    this.$set(this.topicList[index], 'answerOptions', [answer]);
                    break;
                }
            case 'TF':
                this.$set(this.topicList[index], 'answerJudgment', answer);
                break;
            case 'MC_AND':
                _answer = this.topicList[index].options[answer - 1].id;
                if (this.topicList[index].shuffle && this.topicList[index].shuffle === 'Y') {
                    if (!this.topicList[index].answerOptions) {
                        this.$set(this.topicList[index], 'answerOptions', [_answer]);
                    } else {
                        let arr = new Set(this.topicList[index].answerOptions);
                        if (arr.has(_answer)) {
                            arr.delete(_answer);
                        } else {
                            arr.add(_answer);
                        }
                        this.$set(this.topicList[index], 'answerOptions', [...arr]);
                    }
                    break;
                } else {
                    if (!this.topicList[index].answerOptions) {
                        this.$set(this.topicList[index], 'answerOptions', [answer]);
                    } else {
                        let arr = new Set(this.topicList[index].answerOptions);
                        if (arr.has(_answer)) {
                            arr.delete(answer);
                        } else {
                            arr.add(answer);
                        }
                        this.$set(this.topicList[index], 'answerOptions', [...arr]);
                    }
                    break;
                }
            case 'FB':
                let arr = [];
                let errors = [];
                for (let i of this.$refs[answer]) {
                    if (this.checkingSize(i.innerHTML, 400, index)) {
                        errors.push(i.getAttribute('name'));
                        this.$refs['fb' + 'Error' + i.getAttribute('name')][0].style.display = 'block';
                    } else {
                        errors.splice(0, errors.indexOf(i.getAttribute('name')));
                        this.$refs['fb' + 'Error' + i.getAttribute('name')][0].style.display = 'none';
                    };
                    arr.push(i.innerHTML);
                }
                if (errors.length === 0) {
                    if (this.errorList.includes(index)) {
                        this.errorList.splice(this.errorList.indexOf(index), 1);
                    }
                } else {
                    if (!this.errorList.includes(index)) {
                        this.errorList.push(index);
                    }
                }
                this.$set(this.topicList[index], 'answerFillBlank', arr);
                break;
            case 'ES':
                if (this.checkingSize(this.$refs[answer][0].innerHTML, 2000)) {
                    if (!this.errorList.includes(index)) {
                        this.errorList.push(index);
                    }
                    this.$refs['es' + 'Error' + id][0].style.display = 'block';
                } else {
                    if (this.errorList.includes(index)) {
                        this.errorList.splice(this.errorList.indexOf(index), 1);
                    }
                    this.$refs['es' + 'Error' + id][0].style.display = 'none';
                };
                this.$set(this.topicList[index], 'answerShort', this.$refs[answer][0].innerHTML);
                break;
            case 'SR':
                this.$set(this.topicList[index], 'answerShort', answer.answer.answerShort);
                break;
            }
            console.log('this.topicList[index]----', this.topicList[index]);
            this.getAnswered(index);
        },
        /**
         * 情景题选择答案
         * @param type
         * @param answer
         * @param id
         * @param index
         */
        siSelectAnswer(type, answer, id, index, index1) {
            //选择题乱序
            let _answer;
            switch (type) {
            case 'MC':
                _answer = this.topicList[index].questionInfoList[index1].options[answer - 1].id;
                if (this.topicList[index].questionInfoList[index1].shuffle && this.topicList[index].questionInfoList[index1].shuffle === 'Y') {
                    this.$set(this.topicList[index].questionInfoList[index1], 'answerOptions', [_answer]);
                    break;
                } else {
                    this.$set(this.topicList[index].questionInfoList[index1], 'answerOptions', [answer]);
                    break;
                }
            case 'TF':
                this.$set(this.topicList[index].questionInfoList[index1], 'answerJudgment', answer);
                break;
            case 'MC_AND':
                _answer = this.topicList[index].questionInfoList[index1].options[answer - 1].id;
                if (this.topicList[index].questionInfoList[index1].shuffle && this.topicList[index].questionInfoList[index1].shuffle === 'Y') {
                    if (!this.topicList[index].questionInfoList[index1].answerOptions) {
                        this.$set(this.topicList[index].questionInfoList[index1], 'answerOptions', [_answer]);
                    } else {
                        let arr = new Set(this.topicList[index].questionInfoList[index1].answerOptions);
                        if (arr.has(_answer)) {
                            arr.delete(_answer);
                        } else {
                            arr.add(_answer);
                        }
                        this.$set(this.topicList[index].questionInfoList[index1], 'answerOptions', [...arr]);
                    }
                    break;
                } else {
                    if (!this.topicList[index].questionInfoList[index1].answerOptions) {
                        this.$set(this.topicList[index].questionInfoList[index1], 'answerOptions', [answer]);
                    } else {
                        let arr = new Set(this.topicList[index].questionInfoList[index1].answerOptions);
                        if (arr.has(_answer)) {
                            arr.delete(answer);
                        } else {
                            arr.add(answer);
                        }
                        this.$set(this.topicList[index].questionInfoList[index1], 'answerOptions', [...arr]);
                    }
                    break;
                }
            case 'FB':
                let arr = [];
                let errors = [];
                for (let i of this.$refs[answer]) {
                    if (this.checkingSize(i.innerHTML, 400, index)) {
                        errors.push(i.getAttribute('name'));
                        this.$refs['fb' + 'Error' + i.getAttribute('name')][0].style.display = 'block';
                    } else {
                        errors.splice(0, errors.indexOf(i.getAttribute('name')));
                        this.$refs['fb' + 'Error' + i.getAttribute('name')][0].style.display = 'none';
                    };
                    arr.push(i.innerHTML);
                }
                if (errors.length === 0) {
                    if (this.errorList.includes(index)) {
                        this.errorList.splice(this.errorList.indexOf(index), 1);
                    }
                } else {
                    if (!this.errorList.includes(index)) {
                        this.errorList.push(index);
                    }
                }
                this.$set(this.topicList[index].questionInfoList[index1], 'answerFillBlank', arr);
                break;
            case 'ES':
                if (this.checkingSize(this.$refs[answer][0].innerHTML, 2000)) {
                    if (!this.errorList.includes(index)) {
                        this.errorList.push(index);
                    }
                    this.$refs['es' + 'Error' + id][0].style.display = 'block';
                } else {
                    if (this.errorList.includes(index)) {
                        this.errorList.splice(this.errorList.indexOf(index), 1);
                    }
                    this.$refs['es' + 'Error' + id][0].style.display = 'none';
                };
                this.$set(this.topicList[index].questionInfoList[index1], 'answerShort', this.$refs[answer][0].innerHTML);
                break;
            case 'SR':
                this.$set(this.topicList[index].questionInfoList[index1], 'answerShort', answer.answer.answerShort);
                break;
            }
            console.log('this.topicList[index]----', this.topicList[index]);
            this.getAnswered(index);
        },
        /**
         * 配对题弹层选择
         * @param list
         * @param id
         */
        mtTipsCLick(list, id, index, siIndex) {
            this.mtTips = true;
            this.mtOption = list;
            this.mtOption.index = index;
            this.siIndex = siIndex;
        },
        mtConfirm(answer) {
            let obj = {};
            obj[this.mtOption.index] = answer;
            if (!this.mtOption.answerMatching) {
                this.$set(this.mtOption, 'answerMatching', {...obj});
            } else {
                for (let item in this.mtOption.answerMatching) {
                    if (this.mtOption.answerMatching[item] === answer) {
                        this.$delete(this.mtOption.answerMatching, item);
                    }
                }
                this.$set(this.mtOption, 'answerMatching', {...this.mtOption.answerMatching, ...obj});
            };
            this.mtTips = false;
            this.getAnswered(this.siIndex);
        },
        matchingImg(imgUrl) {
            if (imgUrl.indexOf('../') === 0) {
                return imgUrl.replace('../../..', this.appUrl);
            } else {
                return this.appUrl + imgUrl;
            }
        },
        removeNullProperties(arr) {
            const newArr = JSON.parse(JSON.stringify(arr)); // 深拷贝，避免修改原数据
            const stack = [...newArr]; // 用栈模拟遍历，避免递归
            while (stack.length > 0) {
                const obj = stack.pop();
                if (typeof obj !== 'object' || obj === null) {
                    continue;
                }
                for (const key in obj) {
                    if (key === 'subject') {
                        delete obj[key];
                    } else if (obj[key] === null) {
                        delete obj[key]; // 删除值为 `null` 的字段
                    } else if (typeof obj[key] === 'object') {
                        stack.push(obj[key]); // 继续遍历子对象或数组
                    }
                }
            }
            return newArr;
        },
        submit(isSub) {
            if (!isSub) {
                this.subTips = true;
                this.confirmBackFlag = true;
                if (this.topicList.length !== this.answered.length) {
                    this.subTips = true;
                    this.subType = this.$t('exam_tips_6'); //还有题目未做完，确定交卷？
                } else {
                    this.subTips = true;
                    this.subType = this.$t('exam_tips_7'); //题目已做完，确定交卷？
                }
            } else {
                if (this.errorList.length >= 1) {
                    this.error = true;
                    return false;
                }
                this.subLoading = true;
                const newQuestions = this.removeNullProperties(this.allInfo.questions);
                this.allInfo.questions = [...newQuestions];
                this.$axios({
                    method: 'POST',
                    url: `/app/exam/cache/submit`,
                    data: {
                        appId: this.appId,
                        examId: this.examId,
                        subId: this.subId,
                        examInfo: this.allInfo,
                        userAnswer: this.getAnswer(),
                        markQuestions: [],
                        remainingTime: this.saveTime
                    }
                }).then(res => {
                    this.subLoading = false;
                    if (res.data.code === 301) {
                        this.sumitErrorTips = true;
                        this.tipsType = this.$t('has_deleted_learning_record'); //报名记录被删除
                    } else if (res.data.code === 601) {
                        this.sumitErrorTips = true;
                        this.tipsType = this.$t('exam_tips_8'); //已经超出提交次数
                    } else if (res.data.code === 500) {
                        this.sumitErrorTips = true;
                        this.tipsType = this.$t('exam_tips_9'); //试卷提交失败
                    } else {
                        const attemptNbr = res.data.results.attemptNbr || 0;
                        this.$router.replace({path: `/testingReport/${this.$route.params.itmId}/${this.$route.params.tkhId}/${this.$route.params.modId}?attemptNbr=${attemptNbr}`});
                    }
                });
            }
        },
        /**
         * 获取的试题的答案
         */
        getAnswer() {
            let obj = {};
            for (let item of this.topicList) {
                switch (item.type) {
                case 'MC':
                    obj[item.id] = {
                        queId: item.id,
                        answerOptions: item.answerOptions || []
                    };
                    break;
                // 填空
                case 'FB':
                    let arr = [];
                    if (item.answerFillBlank === null || !item.answerFillBlank || item.answerFillBlank.length === 0) {
                        let len = item.subject.match(/\[_]/g).length;
                        for (let i = 0; i < len; i++) {
                            arr.push('');
                        }
                    } else {}
                    obj[item.id] = {
                        queId: item.id,
                        answerFillBlank: item.answerFillBlank && item.answerFillBlank.length !== 0 ? item.answerFillBlank : arr
                    };
                    break;
                case 'MT':
                    obj[item.id] = {
                        queId: item.id,
                        answerMatching: item.answerMatching || null
                    };
                    break;
                case 'TF':
                    obj[item.id] = {
                        queId: item.id,
                        answerJudgment: (item.answerJudgment || item.answerJudgment === false) ? item.answerJudgment : null
                    };
                    break;
                case 'ES':
                    obj[item.id] = {
                        queId: item.id,
                        answerShort: item.answerShort || ''
                    };
                    break;
                case 'SR':
                    obj[item.id] = {
                        queId: item.id,
                        answerShort: item.answerShort || ''
                    };
                    break;
                case 'SI':
                    item.questionInfoList.forEach(info => {
                        let siQuestionInfo = {};
                        switch (info.type) {
                        case 'MC':
                            siQuestionInfo = {
                                queId: info.id,
                                answerOptions: info.answerOptions || []
                            };
                            break;
                        // 填空
                        case 'FB':
                            let arr = [];
                            if (info.answerFillBlank === null || !info.answerFillBlank || info.answerFillBlank.length === 0) {
                                let len = info.subject.match(/\[_]/g).length;
                                for (let i = 0; i < len; i++) {
                                    arr.push('');
                                }
                            } else {}
                            siQuestionInfo = {
                                queId: info.id,
                                answerFillBlank: info.answerFillBlank && info.answerFillBlank.length !== 0 ? info.answerFillBlank : arr
                            };
                            break;
                        case 'MT':
                            siQuestionInfo = {
                                queId: info.id,
                                answerMatching: info.answerMatching || null
                            };
                            break;
                        case 'TF':
                            siQuestionInfo = {
                                queId: info.id,
                                answerJudgment: (info.answerJudgment || info.answerJudgment === false) ? info.answerJudgment : null
                            };
                            break;
                        case 'ES':
                            siQuestionInfo = {
                                queId: info.id,
                                answerShort: info.answerShort || ''
                            };
                            break;
                        case 'SR':
                            siQuestionInfo = {
                                queId: info.id,
                                type: info.type,
                                answerShort: info.answerShort || ''
                            };
                        }
                        obj[info.id] = siQuestionInfo;
                    });
                    break;
                }
            }
            return obj;
        },
        getAnswered(index = 0) {
            let arr = [];
            let dataAll = this.getAnswer();
            let answerFillBlankAir = [];
            let siArr = [];
            let data = [];
            this.topicList.map(item => {
                if (item.type === 'SI') {
                    item.questionInfoList.map(items => {
                        data.push(items.id);
                    });
                }
            });

            let topicDataIds = this.topicList[index].type === 'SI' ? this.topicList[index].questionInfoList.map(info => info.id) : [];
            for (let i in dataAll) {
                if (topicDataIds.includes(dataAll[i].queId)) {
                    siArr.push(dataAll[i]);
                    let other = [];
                    siArr.map(item => {
                        if (item.answerMatching ||
                            (item.answerJudgment || item.answerJudgment === false) ||
                            (item.answerOptions && item.answerOptions.length !== 0) ||
                            (item.answerShort)
                        ) {
                            other.push(item);
                        } else if (item.type === 'SR') {
                            other.push(item);
                        } else if (item.answerFillBlank && item.answerFillBlank.length !== 0) {
                            for (var j = 0; j < item.answerFillBlank.length; j++) {
                                if (item.answerFillBlank[j]) {
                                    answerFillBlankAir.push(j);
                                }
                            }
                            if (answerFillBlankAir.length === item.answerFillBlank.length) {
                                other.push(item);
                            }
                            answerFillBlankAir = [];
                        }
                    });
                    if (other.length === this.topicList[index].questionInfoList.length) {
                        this.topicList[index].answer = true;
                    } else {
                        this.topicList[index].answer = false;
                    }
                } else {
                    if (!data.includes(dataAll[i].queId)) {
                        if (dataAll[i].answerMatching) {
                            arr.push(dataAll[i].queId);
                        }
                        if (dataAll[i].answerJudgment || dataAll[i].answerJudgment === false) {
                            arr.push(dataAll[i].queId);
                        }
                        if (dataAll[i].answerOptions && dataAll[i].answerOptions.length !== 0) {
                            arr.push(dataAll[i].queId);
                        }
                        if (dataAll[i].answerFillBlank && dataAll[i].answerFillBlank.length !== 0) {
                            for (var j = 0; j < dataAll[i].answerFillBlank.length; j++) {
                                if (dataAll[i].answerFillBlank[j]) {
                                    answerFillBlankAir.push(j);
                                }
                            }
                            if (answerFillBlankAir.length === dataAll[i].answerFillBlank.length) {
                                arr.push(dataAll[i].queId);
                            }
                            answerFillBlankAir = [];
                        }
                        if (dataAll[i].answerShort) {
                            arr.push(dataAll[i].queId);
                        }
                    }
                }
            }
            this.answered = arr;
            this.topicList.map(item => {
                if (item.answer) {
                    this.answered.push(item.id);
                }
            });
        },
        imgHandle(txt) {
            let parser = new DOMParser();
            let dom = parser.parseFromString(txt, 'text/html');
            // 处理auido标签
            let audioTags = dom.querySelectorAll('audio');
            audioTags.forEach(audioTag => {
                let src = audioTag.getAttribute('src');
                if (src) {
                    audioTag.setAttribute('src', this.appUrl + src);
                }
            });
            // 处理 <video> 标签
            let videoTags = dom.querySelectorAll('video');
            videoTags.forEach(videoTag => {
                let src = videoTag.getAttribute('src');
                if (src) {
                    videoTag.setAttribute('src', this.appUrl + src);
                }
            });
            // 处理 <img> 标签
            let imgTags = dom.querySelectorAll('img');
            imgTags.forEach(imgTag => {
                let src = imgTag.getAttribute('src');
                if (src) {
                    imgTag.setAttribute('src', this.appUrl + src);
                }
            });
            let htmlContent = dom.documentElement.innerHTML;
            htmlContent = htmlContent.replace(/<head>[.\s\S]*?<\/head>/, '').replace(/<body>|<\/body>/g, '');

            return htmlContent;
        },
        /**
         * 显示剩余时间
         * @param data
         */
        getTime(data) {
            var limitTime;
            if (data > 0) {
                limitTime = data;
                this.examIntervalTime = setInterval(() => {
                    limitTime -= 1000;
                    this.saveTime = limitTime;//自动保存时候存储的时间
                    if (this.visibleModal) {
                        clearInterval(this.examIntervalTime);
                    }
                    let hours = parseInt(limitTime / (60 * 60 * 1000));
                    let min = parseInt((limitTime % (60 * 60 * 1000)) / (60 * 1000));
                    let sec = parseInt(((limitTime % (60 * 60 * 1000)) % (60 * 1000)) / 1000);
                    this.timing = min + ':' + sec;
                    if (hours >= 1) {
                        this.timing = hours + ':' + this.timing;//现在剩余的时间
                    }
                    /*
                    if ((limitTime / 1000) % 5 === 0) { //5s保存一次
                        this.autoSave();
                    }
                    */
                    //保存试题
                    if (!this.autoSaveLock) {
                        this.autoSaveLock = true;
                        this.autoSave();
                        setTimeout(() => {
                            this.autoSaveLock = false;
                        }, this.$store.state.config.examAutoSubmitTime);
                    }
                    if (limitTime <= 0) { //时间到了自动提交
                        this.controlTips = true;
                        this.timeOut = true; //标志强制交卷退出状态
                        this.confirmBackFlag = true;
                        clearInterval(this.examIntervalTime);
                    }
                }, 1000);
            } else {
                limitTime = data;
                this.saveTime = limitTime;
                this.timing = this.$t('mod_unlimited_time'); //不限时
                this.examIntervalTime = setInterval(() => {
                    this.autoSave();
                }, this.$store.state.config.examAutoSubmitTime);
            }
        },
        autoSave() {
            let test = this.getAnswer();

            this.$axios({
                method: 'POST',
                url: `/app/exam/cache/provisional/save`,
                data: {
                    appId: this.appId,
                    examId: this.examId,
                    subId: this.subId,
                    examInfo: this.allInfo,
                    userAnswer: this.getAnswer(),
                    markQuestions: [],
                    remainingTime: this.saveTime
                }
            }).then(res => {
                if (!res.data) { //判断是否允许保存
                    this.controlTips = true;
                }
            });
        },
        jumpTopic(index, item) {
            this.error = false;
            this.answerLetter = false;
            if (this.questionType === 'only') {
                this.topicIndex = index;
            } else {
                const scrollTop = this.$refs[index][0].offsetTop - 50;
                const dom = document.getElementById('content-box');
                dom.scrollTo(0, scrollTop);
            }
            this.isFacePhoto();
        },
        back() {
            this.leave = true;
        },
        confirmBack() {
            //确认推出
            this.confirmBackFlag = true;
            this.autoSave();
            this.$router.go(-1);
        },
        checkingSize(value, size) {
            let num = 0;
            for (let i of value) {
                if (value.charCodeAt(i) > 127 || value.charCodeAt(i) === 94) {
                    num += 2;
                } else {
                    num += 1;
                }
            }
            if (num > size) {
                return true;
            } else {
                return false;
            }
        },
        // 滚动事件
        handleScroll() {
            if (this.questionType === 'only') return;
            // console.log('========================================', this.questionType, this.questionType === 'only');
            let dom = document.getElementById('content-box');
            var scrollTop = dom.pageYOffset || dom.scrollTop || dom.scrollTop;
            this.manyFaceList = [];
            // 减80是因为底部那排按钮占位遮挡住了题目，不算滚动到了可视区域
            const height = window.innerHeight - 180;
            // console.log('滚动事件--scrollTop---h和屏幕高度', scrollTop, height);
            this.topicList.forEach((item, index) => {
                const node = this.$refs[index][0] && this.$refs[index][0].offsetTop;
                const nodeHeight = this.$refs[index][0] && this.$refs[index][0].offsetHeight - 50;
                // 判断该题是否出现在可视区域里面
                // console.log('判断该题是否出现在可视区域里面---', index + 1, '距离顶部的距离：', node, '元素高度', nodeHeight);
                if ((scrollTop + height) >= node && node > scrollTop - nodeHeight) {
                    const faceNode = this.faceList ? this.faceList.find(node => Number(node.ufrNode) === (index + 1)) : [];
                    // console.log('当前题目---------', index + 1, '是否弹出人脸---', faceNode);
                    if (faceNode) {
                        if (faceNode.ufrStatus === 'OFF') {
                            this.manyFaceList.push(index);
                        }
                    }
                }
            });
            // console.log('可视区域内需要人脸识别的节点的下标', this.manyFaceList);
            if (this.manyFaceList.length > 0) {
                // 人脸识别
                this.isFacePhoto(this.manyFaceList[0]);
            }
        }
    },
    beforeCreate() {
        that = this;
    },
    created() {
        this.getFaceTime();
    },
    mounted() {
        this.onlineCalculation('ONLINE_EXAM_INC');
        let dom = document.getElementById('content-box');
        dom.addEventListener('scroll', this.handleScroll);
        // 设置人脸识别的busId
        window.localStorage.removeItem('face_busId');
        window.localStorage.setItem('face_busId', this.$route.params.modId);
    },
    // destroyed() {
    // },
    watch: {
        topicList: function() {
            //$nextTick 里面DOM更新是指页面上的数据是最新的数据。
            this.$nextTick(function() {
                for (let i = 0; i < this.topicList.length; i++) {
                    let item = this.topicList[i];
                    if (item.type === 'SI') {
                        item.questionInfoList.map((itemc, index1) => {
                            if (itemc.type === 'ES') {
                                console.log(123);
                                this.siSelectAnswer('ES', `es${itemc.id}`, itemc.id, i, index1);
                            } else if (itemc.type === 'FB') {
                                this.siSelectAnswer('FB', `fb${itemc.id}`, itemc.id, i, index1);
                            }
                        });
                    } else {
                        if (item.type === 'ES') {
                            this.selectAnswer('ES', `es${item.id}`, item.id, i);
                        } else if (item.type === 'FB') {
                            this.selectAnswer('FB', `fb${item.id}`, item.id, i);
                        }
                    }
                }
            });
        }
    },
    filters: {
        //填空
        filterSpace(value, id) {
            let space = value.match(/\[_]/g);
            let blank = that.$t('FB_label'); //填空;
            for (let i = 0; i < space.length; i++) {
                value = value.replace('[_]', `<span style="display: inline-block;padding: 0 10px;border-bottom: 1px solid #333;margin: 0 8px;font-size: 14px;">${blank} ${i + 1}</span>`);
            }
            return value;
        }
    },
    directives: {
        showText: {
            bind(el, binding) {
                el.innerHTML = binding.value ? binding.value : '';
            }
        }
    },
    destroyed() {
        clearInterval(this.examIntervalTime);
        this.onlineCalculation('ONLINE_EXAM_DEC');
    },
    beforeRouteLeave(to, from, next) {
        if (!this.timeOut) {
            this.leave = true;
        }
        let dom = document.getElementById('content-box');
        dom.removeEventListener('scroll', this.handleScroll);
        if (this.confirmBackFlag) {
            clearInterval(this.examIntervalTime);
            next();
        } else {
            if (to.path !== this.$route.path) {
                window.history.pushState(null, null, from.path);
            }
        }
    }
};
</script>

<style scoped lang="less">
.type-si{
    /deep/pre{
        white-space: pre-wrap;
    }
}
    .errorList{
        width: 32px;
        height: 32px;
        float: left;
        margin: 10px 10px;
        border-radius: 100%;
        border: 1px solid #cccccc;
        text-align: center;
        line-height: 32px;
        background: #075ebb;
        color: #ffffff;
    }
    .exam-nav{
        background: #ffffff;
        overflow: hidden;
        height: 44px;
        line-height: 44px;
        &>div:first-child{
            float: left;
            color: #999999;
            &>p{
                float: left;
            }
         }
        &>div:last-child{
            float: right;
        }
    }
    .exam-foot{
        height: 56px;
        background: #ffffff;
        border-top: 1px solid #cccccc;
        position: absolute;
        bottom: 0;
        width: 100%;
        display: flex;
        padding: 0 16px;
        box-sizing: border-box;
        &>div:first-child{
            width: 90px;
            display: flex;
            align-items: center;
            flex-direction: column;
            justify-content: center;
            text-align: center;
            &:before{
                content: '';
                display: block;
                width: 20px;
                height: 20px;
                background: url(./images/course-icon.png) no-repeat 0 -246px;
                background-size: 20px;
            }
        }
        &>div:last-child{
            display: flex;
            align-items: center;
            &>div{
                &.cur{
                    color: #cccccc;
                    background: #ffffff;
                }
                width: 120px;
                height: 40px;
                text-align: center;
                line-height: 40px;
                border: 1px solid #dddddd;
                border-radius: 8px;
                &:last-child{
                    &.cur{
                        color: #cccccc;
                        background: #ffffff;
                    }
                    background: #075ebb;
                    color: #ffffff;
                    margin-left: 15px;
                }
            }
        }
    }
    .topic-fb{
        &>div:first-child{
            margin-bottom: 25px;
        }
        .fb-space{
            padding: 10px 15px;
            border: 1px solid #dddddd;
            margin: 5px 0;
            &:empty:before{
                content: attr(placeholder);
                color:#999;
            }
            &:focus:before{
                content:none;
            }
        }
    }
    .topic-es{
        .topic-es-box {
            margin-top: 25px;
            min-height: 150px;
            border: 1px solid #dddddd;
            padding: 10px;
            &:empty:before{
                content: attr(placeholder);
                color:#999;
            }
            &:focus:before{
                content:none;
            }
        }
    }
    .topic-mt{
        .topic-mt-matching{
            .topic-mt-matching-btn{
                display: inline-block;
                padding: 5px 15px;
                background: #075ebb;
                color: #ffffff;
            }
        }
    }
    /*单选题*/
    .module-list-06{
        li{
            color: #999999;
            font-size: 14px;
            border: 1px solid #e6e6e6;
            border-radius: 2px;
            padding: 15px 15px 15px 45px;
            margin-bottom: 15px;
            &:nth-last-child(1){
                margin-bottom: 0;
            }
            &.cur{
                background: #f5f8fe;
                border-color: #075ebb;
                color: #075ebb;
            }
        }
        &.selection-01 {
            li{
                display: inline-flex;
                align-items: center;
                width: 100%;
                box-sizing: border-box;
                i{
                    float: left;
                    margin-left: -30px;
                    width: 20px;
                    height: 20px;
                    background: url(../../../static/images/icon-04.png) no-repeat 0 -96px;
                    background-size: 20px;
                    flex-shrink: 0;
                    align-self: flex-start;
                    margin-right: 10px;
                }
                &.cur{
                    i{
                        background-position: 0 -156px;
                    }
                }
            }
        }
        &.selection-02{
            li{
                display: inline-flex;
                align-items: center;
                width: 100%;
                box-sizing: border-box;
                i{
                    float: left;
                    margin-left: -30px;
                    width: 20px;
                    height: 20px;
                    background: url(../../../static/images/icon-04.png) no-repeat 0 -126px;
                    background-size: 20px;
                    flex-shrink: 0;
                    align-self: flex-start;
                    margin-right: 10px;
                }
                &.cur{
                    i{
                        background-position: 0 -186px;
                    }
                }
            }
        }
    }
    .module-list-06.selection-01.mt-selection {
        max-height: 400px;
        overflow-y: auto;
        padding: 0 25px;
    }
    .answer-letter{
        position: fixed;
        width: 100%;
        height: 100%;
        top: 0;
        bottom: 0;
        background: rgba(0,0,0,.5);
        .answer-letter-content{
            position: absolute;
            background: #ffffff;
            width: 100%;
            bottom: 0;
        }
        .answer-letter-title{
            padding: 10px 15px;
            font-size: 18px;
        }
        .answer-letter-tip{
            overflow: hidden;
            padding: 10px 15px;
            div{
                float: left;
                color: #cccccc;
                &:first-child{
                    margin-right: 20px;
                    &:before{
                        content: '';
                        display: inline-block;
                        width: 12px;
                        height: 12px;
                        background: #5084EC;
                        margin: 0 5px -2px 0;
                        border-radius: 100%;
                    }
                }
                &:last-child{
                    &:before{
                        content: '';
                        display: inline-block;
                        width: 12px;
                        height: 12px;
                        border: 1px solid #cccccc;
                        margin: 0 5px -2px 0;
                        border-radius: 100%;
                    }
                }
            }
        }
        .answer-letter-list{
            max-height: 300px;
            overflow: auto;
            li{
                width: 32px;
                height: 32px;
                float: left;
                margin: 10px;
                border-radius: 100%;
                border: 1px solid #cccccc;
                text-align: center;
                line-height: 32px;
                &.cur{
                    background: #075ebb;
                    color: #ffffff;
                }
            }
        }
        /deep/.van-dialog__header--isolated {
            padding: 24px 20px;
        }
    }
    .loading{
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 999;
        &>div{
            width: 112px;
            height: 112px;
            background: rgba(0,0,0,.5);
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            color: #ffffff;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            border-radius: 16px;
            &>div:first-child{
                margin-bottom: 5px;
            }
        }
    }
    /deep/ img{
        width: 100%;
    }
</style>
